package ch.fhnw.qualiscan.application.pages.tabs;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import ch.fhnw.qualiscan.Config;
import ch.fhnw.qualiscan.application.pages.Dashboard;
import ch.fhnw.qualiscan.core.db.helpers.dashboardTableArgs;
import ch.fhnw.qualiscan.core.db.pojos.Domain;
import ch.fhnw.qualiscan.core.db.pojos.DomainText;
import ch.fhnw.qualiscan.core.db.pojos.Question;
import ch.fhnw.qualiscan.core.db.pojos.Survey;
import ch.fhnw.qualiscan.core.db.pojos.SurveyUserRole;

import com.vaadin.data.util.BeanItemContainer;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Component;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Table;
import com.vaadin.ui.VerticalLayout;

import eu.livotov.tpt.i18n.TM;

@SuppressWarnings("serial")
public class DashboardTab1 extends VerticalLayout {

	private Dashboard dashboard;
	private BeanItemContainer<dashboardTableArgs> tableContainer;
	private Table surveyTable;
	
	public DashboardTab1(Dashboard dashboard) {
		this.dashboard = dashboard;
		tableContainer = new BeanItemContainer<dashboardTableArgs>(dashboardTableArgs.class);
		
		List<SurveyUserRole> surList = dashboard.surveyModel.getSurListByUser(dashboard.user);
		for(int i = 0; i < surList.size(); i++) {
			String surveyRole = dashboard.userModel.getRoleText(surList.get(i).getRole(), dashboard.userSession.getLanguage()).getTitle();
			String surveyStage = dashboard.surveyModel.getStageText(surList.get(i).getSurvey().getStage(), dashboard.userSession.getLanguage()).getTitle();
			
			dashboardTableArgs dta = new dashboardTableArgs(surList.get(i), surList.get(i).getSurvey().getTitle(), surveyRole, surList.get(i).getSurvey().getCategory().getTitle(), surList.get(i).getSurvey().getCompletiondate(), surveyStage, surList.get(i).getSurvey().getUniversity().getTitle());
			tableContainer.addBean(dta);
		}
		
		buildLayout();
	}
	
	public void buildLayout() {
		
		// table wrapper
		VerticalLayout tableWrapper = new VerticalLayout();
		tableWrapper.setSpacing(true);
		tableWrapper.setMargin(true);
		
		if(tableContainer.size() > 0) {
			tableWrapper.addComponent(dashboard.textHelper.p(TM.get("dashboard.tab1.desc1")));
			// add table to tableWrapper
			tableWrapper.addComponent(buildTable());
		} else {
			tableWrapper.addComponent(dashboard.textHelper.p(TM.get("dashboard.tab1.desc2")));
		}
		
		addComponent(tableWrapper);
	}
	
	public Table buildTable() {
		surveyTable = new Table();
		surveyTable.setWidth("100%");
		surveyTable.setPageLength(0);
		surveyTable.setSelectable(false);
		
		/*
		 * Generated Column for Button
		 */
		surveyTable.addGeneratedColumn("surveyEditButton", new Table.ColumnGenerator() {
			public Component generateCell(Table source, Object itemId, Object columnId) {
				HorizontalLayout buttonBar = new HorizontalLayout();
				buttonBar.setSpacing(true);
				
				final SurveyUserRole sur = (SurveyUserRole) source.getContainerProperty(itemId, "sur").getValue();
				
				// edit button
				Button editButton = new Button(TM.get("action.edit"));
				editButton.setData(sur.getId());
				editButton.addListener(new Button.ClickListener() {
					public void buttonClick(ClickEvent event) {
						dashboard.urlLib.setFragment("EditSurvey/0/"+event.getButton().getData().toString()+"/", true);
					}
				});	
				editButton.setIcon(Config.ICON_SURVEYEDIT);
				editButton.setWidth("100px");
				
				// results button
				Button evaluationButton = new Button(TM.get("action.evaluate"));
				evaluationButton.setData(sur.getId());
				evaluationButton.addListener(new Button.ClickListener() {
					public void buttonClick(ClickEvent event) {
						dashboard.urlLib.setFragment("Evaluation/0/"+event.getButton().getData().toString()+"/", true);
					}
				});
				evaluationButton.setIcon(Config.ICON_DETAILCHART);
				evaluationButton.setWidth("100px");
				
				// fillout button
				Button filloutButton = new Button(TM.get("action.participate"));
				filloutButton.setData(sur.getId());
				filloutButton.addListener(new Button.ClickListener() {
					public void buttonClick(ClickEvent event) {
						if (sur.getRole().getId() == Config.COORDINATOR_ID) {
							dashboard.urlLib.setFragment("EditSurvey/1/"+event.getButton().getData().toString() + "/", true);
						} else {
							dashboard.urlLib.setFragment("EditSurvey/0/"+event.getButton().getData().toString() + "/", true);
						}
					}
				});
				filloutButton.setIcon(Config.ICON_EDIT);
				filloutButton.setWidth("100px");
				
				buttonBar.addComponent(filloutButton);
				buttonBar.addComponent(evaluationButton);
				buttonBar.addComponent(editButton);
				
				if (sur.getSurvey().getStage().getId() == Config.STAGE_SURVEY) {
					if (sur.getRole().getId() != Config.COORDINATOR_ID  && sur.getRole().getId() != Config.EXPERT_ID) {
						evaluationButton.setEnabled(false);
					}
				}
				
				if(sur.getRole().getId() != Config.COORDINATOR_ID) {
					buttonBar.removeComponent(editButton);
				}
				
				if(sur.getSurvey().getStage().getId() >= Config.STAGE_EVALUATION) {
					//buttonBar.removeComponent(filloutButton);
					filloutButton.setEnabled(false);
				}
				
				if(sur.getSurvey().getStage().getId() >= Config.STAGE_COMPLETED) {
					//buttonBar.removeComponent(filloutButton);
					editButton.setEnabled(false);
				}
				
				if(sur.getRole().getId() == Config.EXPERT_ID) {
					buttonBar.removeComponent(editButton);
					buttonBar.removeComponent(filloutButton);
				}
				
				return buttonBar;
			}
		});
		
		
		surveyTable.setContainerDataSource(tableContainer);
		
		surveyTable.setColumnHeader("surveyTitle", TM.get("dashboard.tab1.table.title"));
		surveyTable.setColumnHeader("surveyRole", TM.get("dashboard.tab1.table.role"));
		surveyTable.setColumnHeader("surveyCategory", TM.get("dashboard.tab1.table.category"));
		surveyTable.setColumnHeader("surveyCompletionDate", TM.get("dashboard.tab1.table.completion"));
		surveyTable.setColumnHeader("surveyStage", TM.get("dashboard.tab1.table.stage"));
		surveyTable.setColumnHeader("surveyEditButton", TM.get("action.actions"));
		surveyTable.setColumnHeader("surveyUniversity", TM.get("dashboard.tab1.table.university"));
		
		surveyTable.setVisibleColumns(new Object[]{"surveyTitle", "surveyRole", "surveyUniversity", "surveyStage", "surveyCompletionDate", "surveyEditButton"});
		
		surveyTable.setSortContainerPropertyId("surveyCompletionDate");
		surveyTable.setSortAscending(true); 
		
		surveyTable.setCellStyleGenerator(new Table.CellStyleGenerator() {
			public String getStyle(Object itemId, Object propertyId) {
				if (propertyId != null) {
					dashboardTableArgs dta = (dashboardTableArgs) itemId;
					String columnName = (String) propertyId;
					
					//Style Role column
					if (columnName.equals("surveyRole")) {
						return "role-style role"+dta.getSur().getRole().getId()+"";
					}
					
					//Style CompletioDate column
					if(columnName.equals("surveyCompletionDate")) {
						if (dta.getSur().getRole().getId() != Config.EXPERT_ID) {
							if (!surveyFilledOut(dta.getSur()) && dta.getSur().getSurvey().getStage().getId() == Config.STAGE_SURVEY) {
								return "date-style date1";
							}
						}
					}
				}
				return null;
			}
		});
		
		return surveyTable;
	}
	
	private boolean surveyFilledOut(SurveyUserRole sur) {
		
		boolean isSurveyFinished = true;
		
		Iterator it = sur.getSurvey().getDomains().iterator();	
		while(it.hasNext()) {

			Domain d = (Domain)it.next();
			
			int nQuestions = 0;
			Iterator<Question> questionIterator= d.getQuestions().iterator();
			while (questionIterator.hasNext()) {
				Question q = questionIterator.next();
				if (q.getSubquestions().size() > 0) {
					nQuestions = nQuestions + q.getSubquestions().size();
				}
				else {
					nQuestions++;
				}
			}
			
			int totalAnswers = dashboard.domainModel.getNumberOfAnswersForSurAndDomain(sur, d);
			float progress = (float)totalAnswers/(float)nQuestions;
			if (progress != 1.0) {
				isSurveyFinished = false;
			}
		}
		
		return isSurveyFinished;
	}
}
